package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.pojo.Order;
import com.zhentao.service.OrderService;
import com.zhentao.service.OrderItemService;
import com.zhentao.mapper.OrderMapper;
import com.zhentao.mapper.OrderItemMapper;
import com.zhentao.util.Result;
import com.zhentao.vo.CreateOrderRequest;
import com.zhentao.vo.UpdateOrderRequest;
import org.example.dish_pojo.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
* @author Lenovo
* @description 针对表【order(订单主表)】的数据库操作Service实现
* @createDate 2025-08-14 11:03:07
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{

    @Autowired
    private OrderItemService orderItemService;
    
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    @Transactional
    public Result createOrder(CreateOrderRequest request) {
        try {
            // 创建订单主表记录
            Order order = new Order();
            
            // 生成订单编号（使用时间戳+随机数）
            String orderNo = "ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8);
            order.setOrderNo(orderNo);
            
            // 设置订单基本信息
            order.setUserId(request.getUserId());
            order.setTableId(request.getTableId());
            order.setOrderType(request.getOrderType());
            order.setStatus(request.getStatus() != null ? request.getStatus() : "pending");
            order.setTotalAmount(request.getTotalAmount());
            order.setPayMethod(request.getPayMethod());
            order.setNotes(request.getNotes());
            
            // 设置时间字段为当前时间
            Date now = new Date();
            order.setCreateTime(now);
            
            // 保存订单主表
            boolean orderSaved = this.save(order);
            if (!orderSaved) {
                return Result.error("订单保存失败");
            }
            
            // 保存订单明细
            if (request.getOrderItems() != null && !request.getOrderItems().isEmpty()) {
                for (com.zhentao.vo.OrderItemRequest itemRequest : request.getOrderItems()) {
                    OrderItem orderItem = new OrderItem();
                    orderItem.setOrderId(order.getOrderId());
                    orderItem.setDishId(itemRequest.getDishId());
                    orderItem.setSpecId(itemRequest.getSpecId());
                    orderItem.setTasteId(itemRequest.getTasteId());
                    orderItem.setQuantity(itemRequest.getQuantity());
                    orderItem.setUnitPrice(itemRequest.getUnitPrice());
                    orderItem.setSubtotal(itemRequest.getSubtotal());
                    
                    boolean itemSaved = orderItemService.save(orderItem);
                    if (!itemSaved) {
                        return Result.error("订单明细保存失败");
                    }
                }
            }
            
            return Result.success("订单创建成功", order);
            
        } catch (Exception e) {
            return Result.error("创建订单失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result updateOrder(UpdateOrderRequest request) {
        try {
            // 检查订单是否存在
            Order existingOrder = this.getById(request.getOrderId());
            if (existingOrder == null) {
                return Result.error("订单不存在");
            }
            
            // 更新订单基本信息
            if (request.getUserId() != null) {
                existingOrder.setUserId(request.getUserId());
            }
            if (request.getTableId() != null) {
                existingOrder.setTableId(request.getTableId());
            }
            if (request.getOrderType() != null) {
                existingOrder.setOrderType(request.getOrderType());
            }
            if (request.getStatus() != null) {
                existingOrder.setStatus(request.getStatus());
            }
            if (request.getTotalAmount() != null) {
                existingOrder.setTotalAmount(request.getTotalAmount());
            }
            if (request.getPayMethod() != null) {
                existingOrder.setPayMethod(request.getPayMethod());
            }
            if (request.getNotes() != null) {
                existingOrder.setNotes(request.getNotes());
            }
            
            // 更新订单
            boolean orderUpdated = this.updateById(existingOrder);
            if (!orderUpdated) {
                return Result.error("订单更新失败");
            }
            
            // 如果提供了订单明细，则更新明细
            if (request.getOrderItems() != null && !request.getOrderItems().isEmpty()) {
                // 先删除原有明细
                orderItemService.removeByOrderId(request.getOrderId());
                
                // 重新添加明细
                for (com.zhentao.vo.OrderItemRequest itemRequest : request.getOrderItems()) {
                    OrderItem orderItem = new OrderItem();
                    orderItem.setOrderId(request.getOrderId());
                    orderItem.setDishId(itemRequest.getDishId());
                    orderItem.setSpecId(itemRequest.getSpecId());
                    orderItem.setTasteId(itemRequest.getTasteId());
                    orderItem.setQuantity(itemRequest.getQuantity());
                    orderItem.setUnitPrice(itemRequest.getUnitPrice());
                    orderItem.setSubtotal(itemRequest.getSubtotal());
                    
                    boolean itemSaved = orderItemService.save(orderItem);
                    if (!itemSaved) {
                        return Result.error("订单明细更新失败");
                    }
                }
            }
            
            return Result.success("订单更新成功", existingOrder);
            
        } catch (Exception e) {
            return Result.error("更新订单失败: " + e.getMessage());
        }
    }
}




